package fi.honkalampisaatio.reaktiopeli.game;

import java.awt.Component;
import java.awt.Image;
import java.awt.image.BufferedImage;

import javax.swing.ImageIcon;
import javax.swing.JList;
import javax.swing.ListCellRenderer;

import fi.honkalampisaatio.game.ui.ScalableIconLabel;

public class ImageAndTextComboBoxRenderer extends ScalableIconLabel implements ListCellRenderer<Object> {
	private static final long serialVersionUID = 9164787183203322378L;
	int maxWidth, maxHeight;
	
	public ImageAndTextComboBoxRenderer() {
		maxWidth = 80;
		maxHeight = 80;
	}

	@Override
	public Component getListCellRendererComponent(JList<?> list, Object value,
			int index, boolean isSelected, boolean cellHasFocus) {
        //Get the selected index. (The index param isn't
        //always valid, so just use the value.)
		ScalableIconLabel label = ((ScalableIconLabel)value);

        if (isSelected) {
            setBackground(list.getSelectionBackground());
            setForeground(list.getSelectionForeground());
        } else {
            setBackground(list.getBackground());
            setForeground(list.getForeground());
        }

        
        setText(label.getText());
    	setIcon(createImageIcon(label.getImage()));
        setFont(list.getFont());

        return this;
	}
	
	public void setMaxIconSize(int width, int height)
	{
		maxWidth = width;
		maxHeight = height;
	}
	
	
	/** Returns an ImageIcon, or null if the image was invalid. */
	protected ImageIcon createImageIcon(BufferedImage img) {
		int width, height;
		if(img==null || maxWidth==0 || maxHeight==0)
		{
			return null;
		}
		try {
			if(img.getWidth()/maxWidth > img.getHeight()/maxHeight) {
				width = maxWidth;
				height = -1;
			}
			else {
				width = -1;
				height = (int) (maxHeight);
			}
	        return new ImageIcon(img.getScaledInstance(width, height, 
	        		Image.SCALE_FAST), "icon");
		} catch (Exception e) {
	        System.err.println(e.getMessage());
			return null;
		}
	}

}
